package uz.rt.dicom.data.element;

import uz.rt.dicom.ControlCharacters;
import uz.rt.dicom.Padding;
import uz.rt.dicom.ValueRepresentation;
import uz.rt.dicom.data.ComparableList;
import uz.rt.dicom.data.StringElement;
import uz.rt.dicom.io.DicomIOException;
import uz.rt.dicom.io.DicomInputStream;
import uz.rt.dicom.tag.DicomTag;

import java.io.IOException;

public class LongString extends StringElement implements Comparable<LongString>
{
// --------------------------- CONSTRUCTORS ---------------------------

    public LongString(DicomTag tag)
    {
        super(tag);
        setMaxLength(64);
        setPadding(Padding.SPACE);
    }

// ------------------------ INTERFACE METHODS ------------------------


// --------------------- Interface Comparable ---------------------

    /**
     * The function compares only the following parameters in order:
     * <ul>
     * <li>Dicom tag</li>
     * <li>Value multiplicity</li>
     * <li>Comparable list of data fields</li>
     * </ul>
     *
     * @param o LongString
     * @return A negative integer, zero, or a positive integer as this object is less than, equal to, or greater than
     *         the specified object.
     */
    public int compareTo(LongString o)
    {
        if (!tag.equals(o.getTag())) return tag.compareTo(o.getTag());
        if (!vm.equals(o.getVm())) return vm.compareTo(o.getVm());
        return value.compareTo(o.getValue());
    }

// --------------------- Interface IDataElement ---------------------

    @Override
    public byte[] getVR()
    {
        return ValueRepresentation.IS;
    }

    @Override
    public ValueRepresentation getValueRepresentation()
    {
        return ValueRepresentation.IntegerString;
    }

    public void read(DicomInputStream dicomInputStream, int length) throws IOException
    {
        value = null;
        value = new ComparableList<String>();
        String s = dicomInputStream.readString(length, getCharacterSet()).trim();
        String[] groups = splitValues(s);
        for (String group : groups)
        {
            char c;
            for (int i = 0; i < group.length(); i++)
            {
                c = group.charAt(i);
                if (c == '\\' || c == ControlCharacters.CR || c == ControlCharacters.FF || c == ControlCharacters.LF)
                {
                    value = null;
                    throw new DicomIOException(
                            "Backslash characters or control characters CR, FF and LF " +
                                    "are not allowed in an LongString object.");
                }
            }
            value.add(group.trim());
        }
    }
}
